function [ zap ] = promptAlpha( varargin )
%PROMPTALPHA Prompts user to select traces for 5-alpha summation analysis, 
%runs the analysis and prints .m-file format results
%
% If an argument is specified, it should be a string specifying the
% filename of a single 5-alpha response trace. If none is
% specified, this functions looks for a "currentTrace" variable in the
% workspace and uses its userFcn.filename field, if present - this means it
% works as a qvTrace user function.
%
% Ben Suter 2009-10-12
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

delay = 0.1;
ISI = 0.05;
numPulses = 5;
showFigure = true;

if nargin > 0 && (exist(varargin{1}, 'file') == 2)
    filename = varargin{1};
else
    filename = evalin('base','currentTrace.userFcn.filename');
end

[pathstr, name, ext] = fileparts(filename);

% File selection dialog adapted from selectFilesFromList.m
d = dir(fullfile(pathstr, ['/*' ext]));
fileList = sortrows({d.name}');
initialIndex = strmatch([name ext], fileList, 'exact');
[selection, ok]  = listdlg('PromptString', 'Select Alpha traces', 'OKString', 'Run Alpha', 'SelectionMode', 'multiple', 'ListString', fileList, 'Name', 'Select Alpha traces', 'InitialValue', initialIndex);

if ok
    if length(selection) < 1
        disp('promptAlpha: no traces were selected');
        return;
    end
    
    % Build the array of trace numbers, b/c that's what summarizeAlphaTrains expects
    for i = 1:length(selection)
        fn = fileList(selection(i));
        fn = fn{:}; % convert from 1x1 cell array to fixed-length string
        sto = length(fn)-length(ext);
        sta = sto - 3;
        traceNums(i) = str2num(fn(sta:sto));
    end
    prefix = [ pathstr '/' fn(1:sta-1) ];
    
    % Run the Alpha analysis
    [ peakAmplitudes peakTimes peakRiseTimes summationFactor response t ] = summarizeAlphaTrains_c2(prefix, traceNums, delay, ISI, numPulses, showFigure); 
    result.summationFactor = summationFactor;
    result.summationFactorMean = mean(summationFactor);
    result.summationFactorStd = std(summationFactor);
    result.traceNumes = traceNums;
    
    % Print the results in format for copy-paste into .m-file
    outPrefix = 'map.alpha.';
    disp('% ********** Alpha: temporal summation in 5-alpha train *******')
    fnames = fieldnames(result);
    for n = 1 : size(fnames,1)
        if (max(size(result.(fnames{n})))) == 1
            disp([outPrefix fnames{n} ' = ' num2str(result.(fnames{n})) ';']);
        else
            disp([outPrefix fnames{n} ' = [' num2str(result.(fnames{n})) '];']);
        end
    end

end
